package com.zsj.juc.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/4/19 17:52
 * @description
 */
public class CompletionStageTest03 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        try {
            CompletableFuture<Void> completableFuture =
                    CompletableFuture.supplyAsync(() -> {
                        //如把这里去掉了 main线程会进来 因为处理的太快了 系统优化切换原则
                        try {
                            TimeUnit.MILLISECONDS.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(1 + Thread.currentThread().getName());
                        return "abcd";
                    }, threadPool).thenRun(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(2 + Thread.currentThread().getName());
                    }).thenRun(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(3 + Thread.currentThread().getName());
                    }).thenRun(() -> {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(4 + Thread.currentThread().getName());
                    });
            System.out.println(completableFuture.get(2L, TimeUnit.SECONDS));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }

    }
}
